import json

from django.http import HttpResponse, JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.index.models import IndexUser
from untils.WXLogin_Openid import get_openid
from untils.auth import c2s
from untils.response import ReturnCode, wrap_json_response


# def __auth_by_code(request):
#     """
#     使用微信的code2session接口授权
#     :param request:
#     :return:
#     """
#     response = {}
#     post_data = request.body.decode('utf-8')
#     post_data = json.loads(post_data)
#     app_id = post_data.get('appId').strip()
#     nickName = post_data.get('nickname').strip()
#     gender = post_data.get('gender')
#     code = post_data.get('code').strip()
#     print(nickName)
#     print(gender)
#
#     print(code)
#     print(app_id)
#     if not (app_id and code):
#         response['result_code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
#         response['message'] = '授权失败,需要完整的授权数据.'
#         return JsonResponse(response, safe=False)
#     try:
#         data = c2s(app_id, code)
#     except Exception as e:
#         print(e)
#         response['result_code'] = ReturnCode.FAILED
#         response['message'] = 'authorized failed.'
#         return JsonResponse(response, safe=False)
#
#
#
#     # ------------------------------------------------
#
#     open_id = data.get('openid')
#     if not open_id:
#         response['result_code'] = ReturnCode.FAILED
#         response['message'] = 'authorization error.'
#         return JsonResponse(response, safe=False)
#
#     # -------------------------------------
#     request.session['open_id'] = open_id
#     request.session['is_Authorized'] = True
#
#     print("open_id:", open_id)
#     # User.objects.get(open_id=open_id)
#     # 如果用户不存在，则新建用户
#     try:
#         user = IndexUser.objects.filter(open_id=open_id)
#     except :
#         user = IndexUser(open_id=open_id, nickName=nickName,gender=gender)
#         user.save()
#
#
#     message = '用户授权成功'
#     response = wrap_json_response(data={}, code=ReturnCode.SUCCESS, message=message)
#     return JsonResponse(response, safe=False)
#
#
# def IndexView(request):
#     """用户验证"""
#     return __auth_by_code(request)


class IndexView(APIView):
    def post(self, request):
        try:
            nickName = request.data.get('nickname')
            gender = request.data.get('gender')
            code = request.data.get('code')
            openid = get_openid(code)
            try:
                user = IndexUser.objects.get(open_id=openid)
            except:
                user = IndexUser.objects.create(
                    username=nickName,
                    nickname=nickName,
                    gender=gender,
                    open_id=openid
                )

            # 服务器生成jwt token, 保存当前用户的身份信息
            from rest_framework_jwt.settings import api_settings

            # 组织payload数据的方法
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            # 生成jwt token数据的方法
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 组织payload数据
            payload = jwt_payload_handler(user)
            # 生成jwt token
            token = jwt_encode_handler(payload)

            data = {
                "errno": 0,
                "data": {
                    "userInfo": {
                        "nickName": user.nickname,
                    },
                    "token": token
                },
                "errmsg": "成功"
            }

            return Response(data)
        except Exception as e:
            print(e)
            return Response()
